/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 15.1.2009, 22:13:18
 */

package imageCutter;

import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.ProgressMonitor;
import javax.swing.UIManager;

/**
 *
 * @author menion
 */
public class MainFrame extends javax.swing.JFrame implements PropertyChangeListener {

	private static final long serialVersionUID = 1L;
	
	private ImageManipulator imageManip;
    public ProgressMonitor progressMonitor;

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        setComponentsEnable(false);
        setLocation(100, 100);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Invoked when task's progress property changes.
     */
    public void propertyChange(PropertyChangeEvent evt) {
//System.out.println(evt.getPropertyName() + ": " + evt.getNewValue());
        if ("progress".equals(evt.getPropertyName())) {
            int progress = (Integer) evt.getNewValue();
            progressMonitor.setProgress(progress);
            String message = String.format("Completed %d%%.\n", progress);
            progressMonitor.setNote(message);
//            taskOutput.append(message);
            if (progressMonitor.isCanceled() || imageManip.isDone()) {
                Toolkit.getDefaultToolkit().beep();
                if (progressMonitor.isCanceled()) {
                    imageManip.cancel(true);
                    jLabel_error.setText("Task canceled.\n");
                } else {
                    jLabel_error.setText("Task completed.\n");
                }
                setComponentsEnable(false);
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField_mapName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField_imagePath = new javax.swing.JTextField();
        jButton_imageSet = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextField_outputPath = new javax.swing.JTextField();
        jButton_outputSet = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jComboBox_tileSizeX = new javax.swing.JComboBox();
        jComboBox_tileSizeY = new javax.swing.JComboBox();
        jButton_do = new javax.swing.JButton();
        jLabel_error = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ImageCutter 0.1 Beta");

        jLabel1.setText("Map pack name");

        jLabel2.setText("File to cut");

        jTextField_imagePath.setEditable(false);

        jButton_imageSet.setText("Select");
        jButton_imageSet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_imageSetActionPerformed(evt);
            }
        });

        jLabel3.setText("Output directory");

        jButton_outputSet.setText("Select");
        jButton_outputSet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_outputSetActionPerformed(evt);
            }
        });

        jLabel4.setText("Tile size");

        jButton_do.setText("OK");
        jButton_do.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_doActionPerformed(evt);
            }
        });

        jLabel_error.setForeground(new java.awt.Color(255, 0, 0));
        jLabel_error.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        jCheckBox1.setText("Compres tiles into TAR");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jCheckBox2.setText("Attach Projection file");
        jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox2ActionPerformed(evt);
            }
        });

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jCheckBox2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE))
                    .addComponent(jCheckBox1)
                    .addComponent(jLabel1)
                    .addComponent(jTextField_mapName, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jTextField_imagePath, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton_imageSet))
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox_tileSizeX, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jComboBox_tileSizeY, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton_do)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel_error, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE)
                        .addGap(57, 57, 57))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jTextField_outputPath, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton_outputSet)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField_mapName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField_imagePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_imageSet))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField_outputPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_outputSet))
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox_tileSizeX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBox_tileSizeY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jCheckBox1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCheckBox2)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel_error)
                    .addComponent(jButton_do))
                .addGap(38, 38, 38))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_imageSetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_imageSetActionPerformed
        JFileChooser fc = new JFileChooser((new File(".")).getAbsolutePath());
        fc.setApproveButtonText("Set");
        fc.setDialogTitle("Choose");
        fc.setMultiSelectionEnabled(false);
        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();

            jTextField_imagePath.setText(file.getAbsolutePath());
            jTextField_outputPath.setText(file.getAbsolutePath().substring(0,
                    file.getAbsolutePath().lastIndexOf(File.separator)));

            imageManip = new ImageManipulator(file, this);

            int[] poss = {2, 3, 5, 7, 9, 11, 13, 17, 19, 23};

            // crate combo box values
            ArrayList<String> pWidth = new ArrayList<String>();
            ArrayList<String> pHeight = new ArrayList<String>();

            for (int i = 0; i < poss.length; i++) {
                int w = imageManip.iWidth;
                int h = imageManip.iHeight;

                while (true) {
                    if (w % poss[i] == 0) {
                        w = w / poss[i];
                        if (!pWidth.contains(String.valueOf(w)) && w > 60)
                            pWidth.add(0, String.valueOf(w));
                    } else {
                        break;
                    }
                }
                
                while (true) {
                    if (h % poss[i] == 0) {
                        h = h / poss[i];
                        if (!pHeight.contains(String.valueOf(h)) && h > 60)
                            pHeight.add(0, String.valueOf(h));
                    } else {
                        break;
                    }
                }
                
            }

            if (!pWidth.contains(String.valueOf(256)))
                pWidth.add(0, String.valueOf(256));
            if (!pHeight.contains(String.valueOf(256)))
                pHeight.add(0, String.valueOf(256));
            if (!pWidth.contains(String.valueOf(250)))
                pWidth.add(0, String.valueOf(250));
            if (!pHeight.contains(String.valueOf(250)))
                pHeight.add(0, String.valueOf(250));
            
            if (pWidth.size() == 0 || pHeight.size() == 0) {
                jLabel_error.setText("Wrong image size !!!");
                return;
            }
            

            String[] data = new String[pWidth.size()];
            for (int i = 0; i < pWidth.size(); i++)
                data[i] = pWidth.get(i);
            Arrays.sort(data);

            DefaultComboBoxModel comboModelX = new DefaultComboBoxModel(data);
            jComboBox_tileSizeX.setModel(comboModelX);
            jComboBox_tileSizeX.setSelectedIndex(0);

            data = new String[pHeight.size()];
            for (int i = 0; i < pHeight.size(); i++)
                data[i] = pHeight.get(i);
            Arrays.sort(data);

            DefaultComboBoxModel comboModelY = new DefaultComboBoxModel(data);
            jComboBox_tileSizeY.setModel(comboModelY);
            jComboBox_tileSizeY.setSelectedIndex(0);

            // set texts
            jTextField_mapName.setText(imageManip.imageFile.getName().substring(0,
                    imageManip.imageFile.getName().lastIndexOf('.')));

            jTextField_outputPath.setText(imageManip.imageFile.getAbsolutePath().substring(0,
                    imageManip.imageFile.getAbsolutePath().lastIndexOf('.')));

            setComponentsEnable(true);
        }
    }//GEN-LAST:event_jButton_imageSetActionPerformed

    private void jButton_outputSetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_outputSetActionPerformed
        JFileChooser fc = new JFileChooser(jTextField_imagePath.getText());
        fc.setApproveButtonText("Set");
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setDialogTitle("Choose output directory");
        fc.setDialogType(JFileChooser.OPEN_DIALOG);
        fc.setMultiSelectionEnabled(false);

        if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            jTextField_outputPath.setText(fc.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_jButton_outputSetActionPerformed

    private void jButton_doActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_doActionPerformed
        String name = jTextField_mapName.getText();
        if (name == null || name.length() < 3) {
            jLabel_error.setText("Unsupported pack name !!!");
            return;
        }

        String outputPath = jTextField_outputPath.getText();
        if (outputPath == null || outputPath.length() < 3) {
            jLabel_error.setText("Unsupported output path !!!");
            return;
        }

        progressMonitor = new ProgressMonitor(MainFrame.this, "Cutting...", "Note?", 0, 100);
        progressMonitor.setProgress(0);

        imageManip.addPropertyChangeListener(this);
        imageManip.setParametres(name, outputPath,
                Integer.parseInt(String.valueOf(jComboBox_tileSizeX.getSelectedItem())),
                Integer.parseInt(String.valueOf(jComboBox_tileSizeY.getSelectedItem())));
        try {
            imageManip.execute();
        } catch (Exception e) {
            System.out.println("Exception: " + e.toString());
        }
        
    }//GEN-LAST:event_jButton_doActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        jCheckBox2.setEnabled(jCheckBox1.isSelected());
        imageManip.compressToTar = jCheckBox1.isSelected();
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox2ActionPerformed
        if (jCheckBox2.isSelected()) {
            JFileChooser fc = new JFileChooser(jTextField_imagePath.getText());
            fc.setApproveButtonText("Set");
            fc.setDialogTitle("Choose config file");
            fc.setDialogType(JFileChooser.OPEN_DIALOG);
            fc.setMultiSelectionEnabled(false);

            if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                imageManip.configFilePath = fc.getSelectedFile().getAbsolutePath();
                jLabel5.setText(fc.getSelectedFile().getAbsolutePath());
            } else {
                jCheckBox2.setSelected(false);
            }
        } else {
            imageManip.configFilePath = null;
            jLabel5.setText("");
        }
    }//GEN-LAST:event_jCheckBox2ActionPerformed

    private void setComponentsEnable(boolean enable) {
        jTextField_mapName.setEnabled(enable);
        jTextField_mapName.setEditable(enable);
        jTextField_outputPath.setEnabled(enable);
        jTextField_outputPath.setEditable(enable);

        jButton_outputSet.setEnabled(enable);
        jButton_do.setEnabled(enable);

        jComboBox_tileSizeX.setEnabled(enable);
        jComboBox_tileSizeY.setEnabled(enable);

        jCheckBox1.setEnabled(enable);
        if (!enable)
            jCheckBox2.setEnabled(enable);

        jLabel1.setEnabled(enable);
        jLabel2.setEnabled(enable);
        jLabel3.setEnabled(enable);
        jLabel4.setEnabled(enable);
        jLabel5.setEnabled(enable);
        jLabel_error.setEnabled(enable);
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        if (args.length == 0) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainFrame().setVisible(true);
                }
            });
        } else {
            String path = "";
            boolean tar = false;
            boolean configFile = false;
            int X = 0;
            int Y = 0;

            for (int i = 0; i < args.length; i++) {
                if (args[i].equalsIgnoreCase("-d")) {
                    i++;
                    path = args[i];
                } else if (args[i].equalsIgnoreCase("-t")) {
                    i++;
                    tar = Boolean.valueOf(args[i]);
                } else if (args[i].equalsIgnoreCase("-c")) {
                    i++;
                    configFile = Boolean.valueOf(args[i]);
                } else if (args[i].equalsIgnoreCase("-x")) {
                    i++;
                    X = Integer.valueOf(args[i]);
                } else if (args[i].equalsIgnoreCase("-y")) {
                    i++;
                    Y = Integer.valueOf(args[i]);
                }

            }

            if (path.equals("") || X == 0 || Y == 0) {
                System.err.println("Wrong parametres!!!!");
                System.out.println("parametres: -d directory -t tar (true, false) -c config(true, false) -x 504 -y 768");
                System.exit(1);
            }

            // batch processing
            File file = new File(path);
            File[] files = file.listFiles();
            int type;
            for (int i = 0; i < files.length - 1; i++) {
                File conf;
                File imag;

                if (files[i].getName().endsWith(".map") && files[i + 1].getName().endsWith(".png")) {
                    conf = files[i];
                    imag = files[i + 1];
                } else if(files[i].getName().endsWith(".png") && files[i + 1].getName().endsWith(".xml")) {
                    conf = files[i + 1];
                    imag = files[i];
                } else {
                    continue;
                }

                ImageManipulator im = new ImageManipulator(imag, null);
                String name = conf.getName().substring(0, conf.getName().lastIndexOf('.'));
                im.setParametres(
                        name,
                        file.getAbsolutePath(),
                        X, Y);
                im.compressToTar = tar;
                if (configFile)
                    im.configFilePath = conf.getAbsolutePath();

                try {
                    im.execute();
                } catch (Exception e) {
                    System.out.println("Exception: " + e.toString());
                }

                while (true) {
                    try {
                        Thread.sleep(1000);
                        if (im.finished)
                            break;
                    } catch (InterruptedException ex) {
                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_do;
    private javax.swing.JButton jButton_imageSet;
    private javax.swing.JButton jButton_outputSet;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JComboBox jComboBox_tileSizeX;
    private javax.swing.JComboBox jComboBox_tileSizeY;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel_error;
    private javax.swing.JTextField jTextField_imagePath;
    private javax.swing.JTextField jTextField_mapName;
    private javax.swing.JTextField jTextField_outputPath;
    // End of variables declaration//GEN-END:variables
}
